//
//  NSObject+GMKVO.m
//  StudyingDemo
//
//  Created by GuoMS on 2018/6/9.
//  Copyright © 2018年 gms. All rights reserved.
//

#import "NSObject+GMKVO.h"
#import <objc/runtime.h>

@implementation NSObject (GMKVO)

- (void)GM_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context {
    
    //1.自定义一个NSKVONotifying_person子类
    NSString *oldClassName =  NSStringFromClass(self.class);
    NSString *newClassName = [@"GMSKVO_"stringByAppendingString:oldClassName];
    //创建一个类
    Class MyClass = objc_allocateClassPair(self.class,newClassName.UTF8String,0);
    //注册该类
    objc_registerClassPair(MyClass);
    
    //动态修改
    object_setClass(self, MyClass);
    
    //添加setName方法  重写父类setAge
    class_addMethod(MyClass, @selector(setAge:), (IMP)kvoage, "v@:");
}

void kvoage(id self,SEL _cmp,NSInteger age) {
    NSLog(@"子类监听方法");
    //通知外部更新这里就不写了
    
}

@end
